"""
coding:utf-8
@describe:项目注册配置文件
@Time:2022/5/28 21:38
@Author:川
"""
import datetime
import os
import logging
import time

from flask import Flask, jsonify
from apps.views import init_view
from apps.pymysql.base import SQLManager
from apps.configs.settings import APP_DEBUG


def create_app():
    """
    :return:
    """
    app = Flask(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

    @app.errorhandler(404)
    def page_not_found(error):
        return jsonify(code=404, msg='The requested URL was not found on the server')

    @app.errorhandler(405)
    def page_not_found(error):
        return jsonify(code=405, msg='The method is not allowed for the requested URL')

    # 日志目录地址
    log_dir_name = "logs%s%s" % (os.sep, datetime.datetime.now().strftime("%Y%m"))
    if not os.path.exists(log_dir_name):
        os.makedirs(log_dir_name, mode=0o755)
    # 日志文件名，以日期作为文件
    log_file_name = 'flask-' + time.strftime('%m-%d', time.localtime(time.time())) + '.log'
    # 创建日志文件名: 目录+文件名
    filename = log_dir_name + os.sep + log_file_name
    # 日志格式:打印日志的时间 - 打印日志级别名称 - 打印当前执行程序的路径 - 打印日志的当前函数 - 打印日志的当前行号 - 打印日志信息
    log_format_str = '%(asctime)s - %(levelname)s - %(pathname)s - %(funcName)s - %(lineno)s - %(message)s'
    # 配置日志,配置日志格式,日志存放文件名称,日志记录等级,日志输出字符类型
    logging.basicConfig(format=log_format_str, filename=filename, level=logging.INFO, encoding='utf-8')
    #  添加日志处理器
    app.logger.addHandler(logging.StreamHandler())

    # 注册路由
    init_view(app)
    app.debug = APP_DEBUG
    return app
